mod province;
mod city;
mod country;

use province::get_province;
use city::get_city;
use country::get_country;

const BASE:[u32;18] = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 0];
const CHECKSUM:[&str;11] = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];

pub fn check_id_card(id_card_no: &str) -> String {
    let len = id_card_no.len();
    if len != 15 && len != 18 {
        return "身份证号码错误".to_owned();
    }
    if len == 18 {
        let rem = id_card_no
            .chars()
            .enumerate()
            .map(|(idx,ch)| BASE[idx] * ch.to_digit(10).unwrap_or(0))
            .sum::<u32>() % 11;
        if &id_card_no[17..] != CHECKSUM[rem as usize] {
            return "身份证号码错误".to_owned();
        }
    }
    let gender_idx = if len == 18 {
        16
    }else {
        14
    };
    let id_card = id_card_no.chars().collect::<Vec<_>>();
    let gender = if id_card[gender_idx].to_digit(10).unwrap()&1==0 {
        "女"
    }else{
        "男"
    };
    let ymd = if len == 18 {
        format!("{}年{}月{}日",&id_card[6..=9].iter().collect::<String>(),&id_card[10..=11].iter().collect::<String>(),&id_card[12..=13].iter().collect::<String>())
    }else{
        format!("19{}年{}月{}日",&id_card[6..=7].iter().collect::<String>(),&id_card[8..=9].iter().collect::<String>(),&id_card[10..=11].iter().collect::<String>())
    };
    let province = get_province(&id_card[0..=1]);
    let city = get_city(&id_card_no[0..=3]);
    let country = get_country(&id_card_no[0..=5]);
    format!("身份证号码正确,{},{},{}-{}-{}",
        gender,
        ymd,
        province,city,country
    )
}
